<!--
  登录页面
  创建时间：2025-09-11
  作者：开发团队
  目的：用户登录认证界面
-->

<template>
  <div class="login-container">
    <div class="login-card">
      <!-- Logo区域 -->
      <div class="logo-section">
        <el-avatar :size="64" class="logo-avatar">
          <el-icon><Lock /></el-icon>
        </el-avatar>
        <h1 class="system-title">新易访内网系统</h1>
        <p class="system-subtitle">访客管理与核验系统</p>
      </div>
      
      <!-- 登录表单 -->
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
        @submit.prevent="handleLogin"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            size="large"
            @keyup.enter="handleLogin"
          >
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            size="large"
            show-password
            @keyup.enter="handleLogin"
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        
        <el-form-item>
          <el-checkbox v-model="loginForm.remember">
            记住密码
          </el-checkbox>
        </el-form-item>
        
        <el-form-item>
          <el-button
            type="primary"
            class="login-btn"
            size="large"
            :loading="authStore.isLoading"
            @click="handleLogin"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { type FormInstance, type FormRules } from 'element-plus'
import { showSuccess } from '@/utils/message'
import { useAuthStore } from '@/stores/auth'
import type { LoginRequest } from '@/types/auth'

// 路由和状态
const router = useRouter()
const authStore = useAuthStore()

// 表单引用
const loginFormRef = ref<FormInstance>()

// 表单数据
const loginForm = ref<LoginRequest>({
  username: '',
  password: '',
  remember: false
})

// 表单验证规则
const loginRules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度为3-20个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度为6-20个字符', trigger: 'blur' }
  ]
}

/**
 * 处理登录
 */
const handleLogin = async (): Promise<void> => {
  if (!loginFormRef.value) return
  
  try {
    // 表单验证
    await loginFormRef.value.validate()
    
    // 执行登录
    console.log('开始登录，登录表单数据:', loginForm.value)
    const success = await authStore.login(loginForm.value)
    console.log('登录结果:', success)
    
    if (success) {
      showSuccess('登录成功')
      console.log('用户信息:', authStore.user)
      console.log('用户角色:', authStore.userRole)
      console.log('认证状态:', authStore.isAuthenticated)
      
      // 根据用户角色跳转到对应页面
      const userRole = authStore.userRole
      console.log('准备跳转，用户角色:', userRole)
      switch (userRole) {
        case 'guard':
          console.log('跳转到门卫页面')
          router.push('/guard')
          break
        case 'admin':
          console.log('跳转到管理员页面')
          router.push('/admin')
          break
        case 'superadmin':
          console.log('跳转到超级管理员页面')
          router.push('/superadmin')
          break
        default:
          console.log('跳转到首页')
          router.push('/')
      }
      console.log('跳转完成')
    } else {
      console.log('登录失败')
    }
  } catch (error) {
    console.error('登录失败:', error)
  }
}

/**
 * 组件挂载时初始化
 */
onMounted(() => {
  // 填充记住的用户名
  const rememberedUsername = authStore.getRememberedUsername()
  if (rememberedUsername) {
    loginForm.value.username = rememberedUsername
    loginForm.value.remember = true
  }
  
  // 如果已登录，直接跳转
  if (authStore.isAuthenticated) {
    const userRole = authStore.userRole
    switch (userRole) {
      case 'guard':
        router.push('/guard')
        break
      case 'admin':
        router.push('/admin')
        break
      case 'superadmin':
        router.push('/superadmin')
        break
      default:
        // 如果用户角色不匹配任何已知角色，保持在登录页面
        console.log('未知用户角色，保持在登录页面')
    }
  }
})
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.login-card {
  width: 100%;
  max-width: 400px;
  background: white;
  border-radius: 12px;
  padding: 40px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
}

.logo-section {
  text-align: center;
  margin-bottom: 32px;
}

.logo-avatar {
  background: var(--el-color-primary);
  color: white;
  margin-bottom: 16px;
}

.system-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

.system-subtitle {
  color: #909399;
  margin: 0;
  font-size: 14px;
}

.login-form {
  width: 100%;
}

.login-btn {
  width: 100%;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .login-card {
    padding: 24px;
    margin: 0 16px;
  }
  
  .system-title {
    font-size: 20px;
  }
}
</style>